package com.example.thread;

import com.example.base.MdcThreadPoolTaskExecutor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author code威
 * @version 1.0
 * @description: TODO
 * @date 2022/7/17 16:13
 */
@Component
@Slf4j
public class ThreadPoolConfig {

    @Bean("myThreadPool")
    public ThreadPoolTaskExecutor myThreadPool(){
        log.info("myThreadPool run...");

        ThreadPoolTaskExecutor taskExecutor = new MdcThreadPoolTaskExecutor();
        //线程池维护先吃的最少数量  服务的核心数
        taskExecutor.setCorePoolSize(4);
        //线程池维护线程的最大数量，  2*核心数
        taskExecutor.setMaxPoolSize(8);
        //缓冲队列，定时任务需要及时执行，不能进行缓存，否则获得锁会有问题
        taskExecutor.setQueueCapacity(1000);
        //允许的空闲时间，当超过了核心线程数之外的线程在空闲时间达到之后会被销毁
        taskExecutor.setKeepAliveSeconds(60);
        //设置线程的前缀名
        taskExecutor.setThreadNamePrefix("myThreadPool-");
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        taskExecutor.initialize();
        return taskExecutor;
    }

}
